//
//  AvatarUtils.swift
//  WechatApp
//
//  Created on 2024.
//

import SwiftUI

/// 获取名称的首字母（支持中文和英文）
func getInitials(_ name: String) -> String {
    if name.isEmpty {
        return "?"
    }
    
    // 移除职位信息（如果有 "-" 分隔符）
    let displayName = name.components(separatedBy: " - ").first?.trimmingCharacters(in: .whitespaces) ?? name
    
    if displayName.isEmpty {
        return "?"
    }
    
    // 如果是中文，取第一个字符
    let firstChar = String(displayName.prefix(1))
    if let scalar = firstChar.unicodeScalars.first, scalar.value > 127 {
        return firstChar.uppercased()
    }
    
    // 如果是英文，取第一个字母
    if let firstLetter = displayName.first, firstLetter.isLetter {
        return String(firstLetter).uppercased()
    }
    
    // 如果都不是，返回第一个字符
    return String(displayName.prefix(1)).uppercased()
}

/// 根据首字母生成颜色
func getAvatarColor(_ initial: String) -> Color {
    let colors: [Color] = [
        .green,      // Green
        .blue,       // Blue
        .purple,     // Purple
        .red,        // Red
        .orange,     // Orange
        .cyan,       // Cyan
        .pink,       // Pink
        .brown,      // Brown
        Color(red: 0.38, green: 0.49, blue: 0.55), // Blue Grey
        Color(red: 0.25, green: 0.32, blue: 0.71), // Indigo
    ]
    
    if let scalar = initial.unicodeScalars.first {
        let index = Int(scalar.value) % colors.count
        return colors[index]
    }
    
    return colors[0]
}

/// 构建首字母头像 View
struct InitialsAvatar: View {
    let name: String
    let size: CGFloat
    
    init(_ name: String, size: CGFloat = 48) {
        self.name = name
        self.size = size
    }
    
    var body: some View {
        ZStack {
            getAvatarColor(getInitials(name))
            
            Text(getInitials(name))
                .font(.system(size: size * 0.4, weight: .bold))
                .foregroundColor(.white)
        }
        .frame(width: size, height: size)
        .clipShape(RoundedRectangle(cornerRadius: size / 12))
    }
}

